<?php

namespace addons\facrm\controller\facrm\product;

use addons\facrm\library\BackendApi;

use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品单位
 * @icon fa fa-circle-o
 */
class Unit extends BackendApi
{

    /**
     * 单位模型对象
     * @var \app\admin\model\facrm\product\Unit
     */
    protected $model = null;
    protected $distinguish = true;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\product\Unit;
        $this->request->filter(['strip_tags']);
    }
    /**
     * 单位列表
     * @ApiBody ("参数参考电脑版")
     */
    public function index()
    {

        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array("rows" => $list);

        return $this->success('', $result);
    }
    /**
     * 编辑单位
     * @ApiParams(name="id", type="int", required=true, description="单位id")
     */
    public function edit() {
        $ids = $this->request->request('id', '', 'intval');
        if (!$ids) {
            $this->error(__('No Results were found'));
        }



        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $row->validateFailException(true)->validate($name . '.edit');
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //更新产品表里的数据
                    $productModel=model('\\app\\admin\\model\\facrm\\product\\Product');
                    $res =$productModel->where("product_unit_id", $ids)
                            ->update(['unit' => $params['name']]);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->success('', $row);
    }
    /**
     * 添加单位
     * @ApiMethod (POST)
     * @ApiBody ("其它参数参考电脑版,去掉row,取里面的")
     */
    public function add()
    {

        $params = $this->request->post();
        if ($params) {
            $result = false;
            Db::startTrans();
            try {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $result = $this->model->validateFailException(true)->validate($name . '.add')->allowField(true)->isUpdate(false)->save($params);
                Db::commit();
            } catch (ValidateException $e) {

                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }
}
